package com.chess.connections.net;

import io.netty.channel.Channel;
import io.netty.channel.ChannelId;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * Created by wusk on 2017/12/12.
 * 存放用户连接
 */
public class ConnectionManager {
    private static final Logger logger = LoggerFactory.getLogger(ConnectionManager.class);
    private Lock lock;
    private Map<String, Channel> clients;

    public ConnectionManager(){
        this.lock = new ReentrantLock();
        clients = new HashMap<>();
    }

    public int clientsSize(){
        return this.clients.size();
    }

    public void put(String id, Channel channel){
        lock.lock();
        this.clients.put(id, channel);
        lock.unlock();
        logger.info("Connections size = {}", clients.size());
    }

    public boolean isOnline(String id) {
        return null != id && clients.containsKey(id);
    }

    public Channel get(String id){
        lock.lock();
        Channel channel = clients.get(id);
        lock.unlock();
        return channel;
    }

    public void removeChannel(ChannelId id){
        lock.lock();
        Set<String> set = clients.keySet();
        for(String key: set){
            Channel channel = clients.get(key);
            if(0 == channel.id().compareTo(id)){
                clients.remove(key);
                lock.unlock();
                return;
            }
        }
        lock.unlock();
    }
}
